<template>
  <div class="glass-system-page">
    <!-- Page Header -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-title">
          <div class="title-icon">
            <svg-icon icon-class="documentation" />
          </div>
          <div class="title-content">
            <h1>信息管理</h1>
            <p>Information Management - 安全隐患信息管理</p>
          </div>
        </div>
        <div class="header-actions">
          <button class="glass-button glass-button--primary" @click="handleAdd" v-hasPermi="['region:region_user:add']">
            <svg-icon icon-class="plus" />
            <span>新增信息</span>
          </button>
        </div>
      </div>
    </div>

    <!-- Statistics Overview -->
    <div class="stats-overview">
      <div class="stats-grid">
        <div class="stat-card-mini glass-card">
          <div class="stat-icon stat-icon--total">
            <svg-icon icon-class="list" />
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ total }}</div>
            <div class="stat-label">总记录数</div>
          </div>
        </div>
        <div class="stat-card-mini glass-card">
          <div class="stat-icon stat-icon--pending">
            <svg-icon icon-class="build" />
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ getStatusCount(0) }}</div>
            <div class="stat-label">待维修</div>
          </div>
        </div>
        <div class="stat-card-mini glass-card">
          <div class="stat-icon stat-icon--completed">
            <svg-icon icon-class="star" />
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ getStatusCount(1) }}</div>
            <div class="stat-label">已维修</div>
          </div>
        </div>
        <div class="stat-card-mini glass-card">
          <div class="stat-icon stat-icon--review">
            <svg-icon icon-class="monitor" />
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ getStatusCount(2) }}</div>
            <div class="stat-label">待审核</div>
          </div>
        </div>
      </div>
    </div>

    <!-- Search Form -->
    <div class="search-form" v-show="showSearch">
      <div class="glass-form">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
          <el-form-item label="区域" prop="regionId">
            <el-tree-select
              v-model="queryParams.region_id2"
              :data="regionOptions"
              :props="{ value: 'id', label: 'name', children: 'children' }"
              value-key="id"
              placeholder="请选择区域"
              check-strictly
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="dict in information_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="检测时间">
            <el-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item>
            <button type="button" class="glass-button glass-button--primary" @click="handleQuery">
              <svg-icon icon-class="search" />
              <span>搜索</span>
            </button>
            <button type="button" class="glass-button" @click="resetQuery" style="margin-left: 8px;">
              <svg-icon icon-class="refresh" />
              <span>重置</span>
            </button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- Action Bar -->
    <div class="action-bar">
      <div class="action-content">
        <div class="action-buttons">
          <button class="glass-button glass-button--danger" :disabled="multiple" @click="handleDelete" v-hasPermi="['information:information:remove']">
            <svg-icon icon-class="delete" />
            <span>删除</span>
          </button>
          <button class="glass-button" @click="handleExport" v-hasPermi="['information:information:export']">
            <svg-icon icon-class="download" />
            <span>导出</span>
          </button>
        </div>
        <div class="action-tools">
          <div class="tool-item" @click="showSearch = !showSearch">
            <svg-icon icon-class="search" />
            <span>显示搜索</span>
          </div>
          <div class="tool-item" @click="getList">
            <svg-icon icon-class="refresh" />
            <span>刷新</span>
          </div>
        </div>
      </div>
    </div>
    <!-- Data Table -->
    <div class="data-table">
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="informationList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="编号" align="center" prop="id" width="80">
            <template #default="scope">
              <span class="issue-id">#{{ scope.row.id }}</span>
            </template>
          </el-table-column>
          <el-table-column label="区域" align="center" min-width="200">
            <template #default="scope">
              <div class="region-info centered-content">
                <svg-icon icon-class="location" class="region-icon" />
                <span>{{ getRegionPath(scope.row.regionId) }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="图片" align="center" prop="picture" width="100">
            <template #default="scope">
              <div class="image-preview-wrapper">
                <image-preview :src="scope.row.picture" :width="50" :height="50" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status" width="100">
            <template #default="scope">
              <span :class="['glass-status-tag', getStatusClass(scope.row.status)]">
                {{ getStatusText(scope.row.status) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="检测时间" align="center" prop="detectionTime" width="160">
            <template #default="scope">
              <div class="time-info">
                <svg-icon icon-class="time" class="time-icon" />
                <span>{{ parseTime(scope.row.detectionTime) }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remarks" show-overflow-tooltip min-width="150">
            <template #default="scope">
              <span class="remarks-text">{{ scope.row.remarks || '暂无备注' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
            <template #default="scope">
              <div class="table-actions">
                <el-tooltip content="查看详情" placement="top">
                  <button class="action-btn action-btn--primary action-btn--wide" @click="handleUpdate(scope.row)" v-hasPermi="['information:information:edit']">
                    <svg-icon icon-class="view" />
                    <span>查看详情</span>
                  </button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <button class="action-btn action-btn--danger" @click="handleDelete(scope.row)" v-hasPermi="['information:information:remove']">
                    <svg-icon icon-class="delete" />
                  </button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- Pagination -->
    <div class="pagination-container">
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改维修信息管理对话框 -->
    <el-dialog :title="title" v-model="open" width="850px" append-to-body>
      <template #header>
        <div style="text-align: center; width: 100%">
          {{ title }}
        </div>
      </template>
      <el-form
        ref="informationRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="区域" prop="regionId">
          <el-tree-select
            v-model="form.regionId"
            :data="regionOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            value-key="id"
            placeholder="请选择区域"
            :check-strictly="false"
            disabled
          />
        </el-form-item>
        <el-form-item label="图片" prop="picture">
          <image-upload v-model="form.picture" :limit="1" disabled />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in information_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="检测人员" prop="detectionBy">
              <el-tree-select
                v-model="form.detectionBy"
                :data="userList.filter((edit) => edit.deptId == 101)"
                :props="{
                  value: 'userId',
                  label: 'nickName',
                  children: 'children',
                }"
                value-key="id"
                placeholder="暂无"
                check-strictly
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="员工编号" prop="detectionBy">
              <el-input
                v-model="form.detectionBy"
                placeholder="暂无"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检测时间" prop="detectionTime">
              <el-date-picker
                clearable
                v-model="form.detectionTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="暂无"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="检测相册">
          <image-upload v-model="listinspec" disabled />
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="8"
            ><el-form-item label="维修人员" prop="maintenanceBy">
              <el-tree-select
                v-model="form.maintenanceBy"
                :data="userList.filter((edit) => edit.deptId == 102)"
                :props="{
                  value: 'userId',
                  label: 'nickName',
                  children: 'children',
                }"
                value-key="id"
                placeholder="暂无"
                check-strictly
                disabled
              /> </el-form-item
          ></el-col>
          <el-col :span="8"
            ><el-form-item label="员工编号" prop="maintenanceBy">
              <el-input
                v-model="form.maintenanceBy"
                placeholder="暂无"
                disabled
              /> </el-form-item
          ></el-col>
          <el-col :span="8"
            ><el-form-item label="维修时间" prop="maintenanceTime">
              <el-date-picker
                clearable
                v-model="form.maintenanceTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="暂无"
                disabled
              >
              </el-date-picker> </el-form-item
          ></el-col>
        </el-row>
        <el-form-item label="维修相册">
          <image-upload v-model="listmaintain" disabled />
        </el-form-item>
        <el-form-item label="备注信息" prop="remarks">
          <el-input
            v-model="form.remarks"
            type="textarea"
            placeholder="暂无备注信息"
            :rows="3"
            disabled
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Information">
import {
  listInformation,
  getInformation,
  delInformation,
  addInformation,
  updateInformation,
} from "@/api/information/information";
import { listRegion } from "@/api/region/region";
import { listUser } from "@/api/system/user";

const { proxy } = getCurrentInstance();
const { information_status } = proxy.useDict("information_status");

const informationList = ref([]);
const regionList = ref([]);
const regionOptions = ref([]);
const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const listinspec = ref(null);
const listmaintain = ref(null);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    regionId: null,
    status: null,
    region_id2: null,
  },
  rules: {
    regionId: [
      { required: true, message: "区域编号不能为空", trigger: "blur" },
    ],
    picture: [{ required: true, message: "图片不能为空", trigger: "blur" }],
    status: [{ required: true, message: "状态不能为空", trigger: "change" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询维修信息管理列表 */
function getList() {
  loading.value = true;
  listInformation(proxy.addDateRange(queryParams.value, dateRange.value)).then((response) => {
    informationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 状态处理方法
function getStatusText(status) {
  // 使用字典数据而不是硬编码映射
  const dict = information_status.value.find(item => item.value == status)
  return dict ? dict.label : '未知'
}

function getStatusClass(status) {
  // 根据状态值返回对应的样式类
  const statusClassMap = {
    '0': 'status-warning',   // 待维修
    '1': 'status-success',   // 已维修
    '2': 'status-info',      // 待审核
    '3': 'status-danger',    // 不通过
    '4': 'status-primary'    // 已接取（如果存在）
  }
  return statusClassMap[status] || 'status-info'
}

// 统计方法
function getStatusCount(status) {
  return informationList.value.filter(item => item.status === status).length
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    regionId: null,
    picture: null,
    status: null,
    detectionBy: null,
    detectionTime: null,
    maintenanceBy: null,
    maintenanceTime: null,
    remarks: null,
  };
  proxy.resetForm("informationRef");
  listinspec.value = null;
  listmaintain.value = null;
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加维修信息管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getInformation(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    listinspec.value = response.data.cInspecAlbumList.map((item) => ({
      name: item.picture,
      url: item.picture,
    }));
    listmaintain.value = response.data.cMaintainAlbumList.map((item) => ({
      name: item.picture,
      url: item.picture,
    }));
    title.value = "维修信息详情";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["informationRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateInformation(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addInformation(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除维修信息管理编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delInformation(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "information/information/export",
    {
      ...queryParams.value,
    },
    `information_${new Date().getTime()}.xlsx`
  );
}
/** 查询区域信息管理列表 */
function getRegionList() {
  loading.value = true;
  listRegion(queryParams.value).then((response) => {
    regionList.value = proxy.handleTree(response.data, "id", "parentId");
    loading.value = false;
  });
}
/** 查询区域信息管理下拉树结构 */
function getRegionTreeselect() {
  listRegion().then((response) => {
    regionOptions.value = proxy.handleTree(response.data, "id", "parentId");
  });
}
function flattenRegionList(nodes) {
  let result = [];
  nodes.forEach((node) => {
    result.push(node);
    if (node.children && node.children.length > 0) {
      result = result.concat(flattenRegionList(node.children));
    }
  });
  return result;
}
function getRegionName(id) {
  const flatRegions = flattenRegionList(regionList.value);
  return flatRegions.find((region) => region.id == id)?.name || id;
}

/** 获取完整的区域路径 */
function getRegionPath(regionId) {
  if (!regionId) return ''
  
  const flatRegions = flattenRegionList(regionList.value)
  const targetRegion = flatRegions.find(region => region.id == regionId)
  
  if (!targetRegion) return regionId
  
  // 构建路径数组
  const path = []
  let currentRegion = targetRegion
  
  // 向上遍历父节点
  while (currentRegion) {
    path.unshift(currentRegion.name) // 添加到数组开头
    if (currentRegion.parentId) {
      currentRegion = flatRegions.find(region => region.id == currentRegion.parentId)
    } else {
      break
    }
  }
  
  return path.join(' - ')
}
//查找节点
function findNodeById(nodes, targetId) {
  for (const node of nodes) {
    if (node.id === targetId) {
      return node;
    }
    if (node.children) {
      const found = findNodeById(node.children, targetId);
      if (found) return found;
    }
  }
  return null;
}
//获取所有子节点 ID
function getAllChildRegionIds(node) {
  let ids = [node.id];
  if (node.children && node.children.length > 0) {
    node.children.forEach((child) => {
      ids = ids.concat(getAllChildRegionIds(child));
    });
  }
  return ids;
}
/** 查询员工列表 */
function getuserList() {
  loading.value = true;
  listUser().then((res) => {
    loading.value = false;
    userList.value = res.rows.filter(
      (edit) => edit.deptId == 101 || edit.deptId == 102
    );
    total.value = res.total;
  });
}
onMounted(() => {
  getuserList();
  getList();
  getRegionList();
  getRegionTreeselect();
});
</script>

<style scoped lang="scss">
@import '@/assets/styles/system-pages.scss';

// Statistics Overview
.stats-overview {
  margin-bottom: 24px;
  
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
    
    .stat-card-mini {
      display: flex;
      align-items: center;
      gap: 16px;
      padding: 20px;
      
      .stat-icon {
        width: 48px;
        height: 48px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        
        svg {
          font-size: 24px;
          color: white;
        }
        
        &.stat-icon--total {
          background: linear-gradient(135deg, var(--accent-primary), var(--accent-secondary));
        }
        
        &.stat-icon--pending {
          background: linear-gradient(135deg, var(--accent-warning), var(--accent-amber));
        }
        
        &.stat-icon--completed {
          background: linear-gradient(135deg, var(--accent-success), #8fbc8f);
        }
        
        &.stat-icon--review {
          background: linear-gradient(135deg, var(--accent-blue), var(--accent-primary));
        }
      }
      
      .stat-content {
        .stat-number {
          font-size: 24px;
          font-weight: 700;
          color: var(--text-primary);
          line-height: 1;
          margin-bottom: 4px;
        }
        
        .stat-label {
          font-size: 12px;
          color: var(--text-secondary);
          font-weight: 500;
        }
      }
    }
  }
}

// Table Enhancements
.issue-id {
  font-weight: 600;
  color: var(--accent-blue);
}

.region-info, .time-info {
  display: flex;
  align-items: center;
  gap: 6px;
  
  .region-icon, .time-icon {
    font-size: 14px;
    color: var(--text-secondary);
  }
}

.image-preview-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
}

.remarks-text {
  font-size: 13px;
  color: var(--text-secondary);
  line-height: 1.4;
}

// 居中显示内容
.centered-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

@media (max-width: 768px) {
  .stats-overview .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>
